package juc.utils.forkjoin;

import java.util.Optional;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

public class ForkJoinRecursiveAction {
    private final static int MAX_THRESHOLD = 3;
    //累加器
    private final static AtomicInteger SUM = new AtomicInteger(0);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //RecursiveTask(有返回值，建议使用这个)、RecursiveAction(无返回值)都是ForkJoinPool调度的
        final ForkJoinPool forkJoinPool = new ForkJoinPool();
        //submit(ForkJoinTask<T> task)
        //异步任务，没有返回值
        forkJoinPool.submit(new CalculateRecursiveAction(0, 10));
        forkJoinPool.awaitTermination(10, TimeUnit.SECONDS);
        Optional.of(SUM).ifPresent(System.out::println);
    }

    private static class CalculateRecursiveAction extends RecursiveAction {

        private final int start;
        private final int end;

        private CalculateRecursiveAction(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected void compute() {
            if (end - start <= MAX_THRESHOLD) {
                //把结果进行累加
                SUM.addAndGet(IntStream.rangeClosed(start, end).sum());
            } else {
                int middle = (start + end) / 2;
                CalculateRecursiveAction leftTask = new CalculateRecursiveAction(start, middle);
                CalculateRecursiveAction rightTask = new CalculateRecursiveAction(middle + 1, end);
                leftTask.fork();
                rightTask.fork();
                //没有返回值，不需要join
            }
        }
    }

}
